import { reactive, ref } from "vue";
import { ElForm } from 'element-plus';
import { DailogModel } from "@/type/BaseType";
import { EditType, Title } from "@/type/BaseEnum"
import userInstance from '@/hooks/userInstance'
import { AddRoleModel } from "@/api/role/roleModel";

export default function addRole(dailog:DailogModel,onShow,onClose,emit) {
    const { global } = userInstance()
    // 表单的ref属性
    const formDataRef = ref<InstanceType<typeof ElForm>>()
    // 表单绑定的数据
    const formData = reactive<AddRoleModel>({
        id: '',
        name: '',
        remark: '',
        createUser: '',
        type: '', // 区分新增/编辑
    })
    // 表单验证规则
    const rules = reactive({
        name: [{
            required: true,
            message: '请输入角色名称',
            trigger: 'change'
        }],
        remark: [{
            required: true,
            message: '请输入角色备注',
            trigger: 'change'
        }]
    })
    // 弹框展示
    const show = (type: string, row: AddRoleModel) => {
        // 设置弹框的属性
        dailog.height = 200
        type === EditType.ADD ? dailog.title = Title.ADD : dailog.title = Title.EDIT
        // type === EditType.ADD ? dailog.title = Title.ADD : dailog.title = Title.EDIT
        onShow()
        // 清空表单
        global.$restForm(formDataRef.value,formData)
        // 如果是编辑，要把编辑的数据复制到表单绑定的formData里面
        if(type === EditType.EDIT) {
            // 回显数据 把row复制到dialogModel
            global.$objCopy(row,formData)
        }
        // 设置是新增还是编辑
        formData.type = type
    }
    // 弹框确定
    const confirm = () => {
        formDataRef.value?.validate(valid => {
            console.log(valid)
            if(valid) {
                emit('save',formData)
                // 关闭弹窗
                onClose()
            }
        })
    }
 
    return {
        formData,
        rules,
        formDataRef,
        show,
        confirm
    }
}